//
//  HXRootViewController.m
//  HXTClient
//
//  Created by lemon on 14-4-4.
//  Copyright (c) 2014年 easaa. All rights reserved.

#import "HXRootViewController.h"
//#import "HXLoginInstance.h"
#import "JsonUtil.h"
//#import "HXWebsiteListModel.h"
//#import "HXDataBaseObject.h"
//#import "HXLeftMenuViewController.h"
//#import "HXTool.h"



#import "ZineViewModelVC.h"
#import "ParentViewModelVC.h"
#import "ArticleViewModelVC.h"





#import "NavRootShowViewContorller.h"


//菜单栏
#import "AttributeModelVC.h"
//顾问列表栏目
#import "ContactViewController.h"
//留言
#import "MessageManagementVC.h"
#import "ZilneView.h"



@interface HXRootViewController () <UIGestureRecognizerDelegate,LeftViewDelegate,ListTableviewDelegate,UITextFieldDelegate, ZilneViewDelegat,UIAlertViewDelegate>
{
    __weak UIView *_leftView;
    __weak UIView *_mainView;
    UIPanGestureRecognizer *_pan;

    UIControl   *_rightBgControl;
    UIControl   *backgroundView;
    
    
    NSInteger           TabbarCount;
    NSMutableArray      *ViewArry;
    NSMutableArray      *ViewimageArry;
    
    
    NSInteger           _ChangNavTag;               //上一次的栏目，用于区别是否点击同一个cell
    
    UIView              *SearchView;//搜索
    UITextField         *TextSearchView;//搜索栏目
   
}

@end

@implementation HXRootViewController

- (void)dealloc
{
    
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
       

    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self)
    {
       
    }
    return self;
}

#pragma mark 切换Tabbarview代理
-(void)ChangMainViewContorllerDataAndUIModelTag:(NSInteger)Tag
{
    
    if( _ChangNavTag!=Tag && Tag<self.ModelData.count)
    {
        CategoryDataModel * mdoeldata = [ self.ModelData objectAtIndex:Tag];
        [self MantabbarGetDataArryforCategory:mdoeldata.children];
        _ChangNavTag = Tag;
    
    }
    
    //收回视图
    [self hideLeftView];
    
}
#pragma mark 切换view tabbar控制器
- (void)AllocalizeSubviewChang:(NSArray *)ManViewCategory
{
    
     self.mainController.viewControllersArray =[[NSArray alloc]initWithArray:ManViewCategory];
     [self.mainController DatachangviewButtonFontion];
    
    self.mainController.normalImageArray=ViewimageArry;

    self.mainController.selectedIndex = 0;

}





#pragma mark 代理回调数据，传过来category的数据，已经从data字段取出
-(void)MantabbarGetDataArryforCategory:(NSArray *)CategoryModelArry
{
 
    
    //提前拿出tabbar个数 布局。
    TabbarCount = CategoryModelArry.count;
    
    [ViewArry removeAllObjects];
    [ViewimageArry removeAllObjects];
  
    
        for (int i = 0; i<TabbarCount; i++)
        {
            CategoryDataModel *mdoelcat = [CategoryModelArry objectAtIndex:i];
            [self DrawingPageForControlsUIandData:mdoelcat addtag:i];
        }
    
    //如果不是nil，则是切换view的动作
    if(self.mainController != nil)
    {
     [self AllocalizeSubviewChang:ViewArry];
    return;
    }
    [self AllocalizeSubview:ViewArry];
}



//此处为进入首页 加载数据、上面是 切换代理
#pragma mark 代理回调数据，传过来category的数据，已经从data字段取出
-(void)guanzhuMantabbarGetDataArryforCategory:(NSArray *)CategoryModelArry
{
    
    
    NSArray  *dataarrysmolde;
    
    NSUserDefaults *UserDefaultSize =[NSUserDefaults standardUserDefaults];
    
    if(![UserDefaultSize integerForKey:YZZX_guanzhu_pindao])
    {
        
        dataarrysmolde = [[NSArray alloc]initWithArray:CategoryModelArry];
        
    }else if ([UserDefaultSize integerForKey:YZZX_guanzhu_pindao])
    {
        int Tagnsinter  = (int)[UserDefaultSize integerForKey:YZZX_guanzhu_pindao];
        
        
        CategoryDataModel * mdoeldata = [self.ModelData objectAtIndex:Tagnsinter];
        dataarrysmolde = [[NSArray alloc]initWithArray:mdoeldata.children];
        
        //创建通知
        NSString *strtag =[NSString stringWithFormat:@"%d",Tagnsinter];
        NSDictionary *dicD =[[NSDictionary alloc]initWithObjectsAndKeys:strtag,@"Tag", nil];
        
        NSNotification *notification =[NSNotification notificationWithName:YZZX_LEFT_CELL_CHANG object:nil userInfo:dicD];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];


    }
    
    
    
    
    //提前拿出tabbar个数 布局。
    TabbarCount = dataarrysmolde.count;
    
    [ViewArry removeAllObjects];
    [ViewimageArry removeAllObjects];
    
    
    for (int i = 0; i<TabbarCount; i++)
    {
        CategoryDataModel *mdoelcat = [dataarrysmolde objectAtIndex:i];
        [self DrawingPageForControlsUIandData:mdoelcat addtag:i];
    }
    
    //如果不是nil，则是切换view的动作
    if(self.mainController != nil)
    {
        [self AllocalizeSubviewChang:ViewArry];
        return;
    }
    [self AllocalizeSubview:ViewArry];
}





#pragma mark 根据传进来model建立UI和传出具体的数据
-(void)DrawingPageForControlsUIandData:(CategoryDataModel *)mdoeldata addtag:(int)tag
{
    
 
    //返回一个viewcontroller
    SuperBarVC * TabbarView = (SuperBarVC *)[CategoryDataModel TabbarViewControllerCategoryModel:mdoeldata];
    //给每个viewcontorller传入一个指针，作为push 详细页面使用
    TabbarView.rootviews=self;
    
    //添加到tabbar数组中
    [ViewArry addObject:TabbarView];
    [ViewimageArry addObject:mdoeldata.image_url];
  
}



#pragma mark 给rootviewcontorller   添加两个子viewcontorller  +  实例化两个viewcontorller
- (void)AllocalizeSubview:(NSArray *)ManViewCategory
{
 
    
    
    self.leftVC = [[LeftViewVC alloc]init];
    //设置代理
    self.leftVC.Leftdelegate = self;
    _leftView = self.leftVC.view;
    [self addChildViewController:self.leftVC];
    _leftView.frame = self.view.bounds;
    [self.view addSubview:_leftView];
    [self.leftVC didMoveToParentViewController:self];
    
    

//        ArticleViewModelVC * ArticleView = [[ArticleViewModelVC alloc]init];
//        ParentViewModelVC * ParentView = [[ParentViewModelVC alloc]init];
//        ZineViewModelVC * ZineView = [[ZineViewModelVC alloc]init];
//        ZineViewModelVC * ZineView1 = [[ZineViewModelVC alloc]init];
    
    self.mainController = [[CustomTabBarViewController alloc] init];
    self.mainController.viewControllersArray =[[NSArray alloc]initWithArray:ManViewCategory];
    
//    NSUserDefaults *UserDefaultSize =[NSUserDefaults standardUserDefaults];
//    [UserDefaultSize setInteger:TagCount forKey:YZZX_guanzhu_pindao];
    
    self.mainController.selectedIndex = 0;
        

    // cusVC.normalImageArray =ViewimageArry;
    
    self.mainController.normalImageArray=ViewimageArry;

    
   _mainView = self.mainController.view;
    [self addChildViewController:self.mainController];
   _mainView.frame = self.view.bounds;
    [self.view addSubview:_mainView];
    [self.mainController didMoveToParentViewController:self];
    
}

#pragma mark 显示viewcontorller
- (void)showLeftView
{
    
    // 创建一个手势，添加到右边的view'上，
    if (_rightBgControl == nil)
    {
        _rightBgControl = [[UIControl alloc] initWithFrame:_mainView.bounds];
        [_rightBgControl addTarget:self action:@selector(rightBgControlAction) forControlEvents:UIControlEventTouchUpInside];
        _rightBgControl.backgroundColor = [UIColor clearColor];
        [_mainView addSubview:_rightBgControl];
    }
    //给手势右移的时候，加一个动画透明度的变化，有亮变黑
    [_rightBgControl.layer addAnimation:[self selfBgShowAnimation] forKey:@"selfBgShowAnimation"];
    //给右边的view做一个动画
    [UIView animateWithDuration:0.35f animations:^{
        _mainView.left = 200;
    } completion:^(BOOL finished) {
        
    }];
}


#pragma mark 隐藏viewcontorller
- (void)hideLeftView
{
    [_rightBgControl.layer addAnimation:[self selfBgHideAnimation] forKey:@"selfBgHideAnimation"];
    [UIView animateWithDuration:0.35f animations:^{
        _mainView.frame = CGRectMake(0, _mainView.top, _mainView.width, _mainView.height);
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark 设置显示viewcontorller的位置
- (void)showLeftViewWithX:(CGFloat)x
{
    CGFloat mainViewX = 0 + x;
    _mainView.frame = CGRectMake(mainViewX, _mainView.top, _mainView.width, _mainView.height);
}


#pragma mark 添加到viewcontorller 上的手势     代理事件
- (void)pan:(UIPanGestureRecognizer *)gesture
{
    static BOOL isShowLeftMenu = NO;
    
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
        {
            CGPoint velocity = [gesture velocityInView:self.view];    //速度，矢量有方向
            HXLog(@"%@", NSStringFromCGPoint(velocity));
            CGPoint localPoint = [gesture locationInView:self.view];
            if (localPoint.x < 40 && _mainView.left == 0)
            {
                isShowLeftMenu = YES;
            } else
            {
                isShowLeftMenu = NO;
            }
            break;
        }
        case UIGestureRecognizerStateChanged:
        {
            //translationInView返回相对起始point的左右偏移量, x:为正则方向向右为负向左
            CGPoint translation = [gesture translationInView:self.view];
            if (isShowLeftMenu && translation.x > 0)
            {
                if (translation.x < 100)
                {
                    [self showLeftViewWithX:translation.x];
                } else
                {
                    [self showLeftView];
                }
            }
            break;
        }
        default:
        {
            if (isShowLeftMenu && _mainView.left < 100)
            {
                [self hideLeftView];
            } else if (isShowLeftMenu && _mainView.left > 100)
            {
                
            }
            break;
        }
    }
}

#pragma mark - UIGestureRecognizerDelegate  添加到viewcontorller 上的手势代理

//- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
//{
//    CGPoint localPoint = [gestureRecognizer locationInView:self.view];
//    if (![self gestureIsEnabe])
//        return NO;
//    if (localPoint.x < 40)
//    {
//        return YES;
//    }
//    return NO;
//}

//- (BOOL)gestureIsEnabe
//{
//    BOOL enable = YES;
//    for (UINavigationController *nc in _mainController.viewControllers)
//    {
//        if (nc.viewControllers.count > 1)
//        {
//            enable = NO;
//        }
//    }
//    return enable;
//}
//

#pragma mark 设置当前rootview 的导航栏，添加导航栏上控件
-(void)NavController
{
    //菜单按钮
    UIButton  *MenuBut = [UIButton buttonWithType:UIButtonTypeCustom];
   
    MenuBut.frame = CGRectMake(0, 0, 30, 25);
    [MenuBut setImage:[UIImage imageNamed:@"night_top_navigation_menuicon@2x"] forState:UIControlStateNormal];
    [MenuBut setImage:[UIImage imageNamed:@"night_top_navigation_menuicon_h@2x"] forState:UIControlStateHighlighted];
    
    [MenuBut addTarget:self action:@selector(Menuseletor:) forControlEvents:UIControlEventTouchUpInside];
    
   
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:MenuBut];
    self.navigationItem.leftBarButtonItem = backItem;
    
//    
//    UIBarButtonItem *negativeSpacerLeft = [[UIBarButtonItem alloc]
//                                       
//                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
//                                       
//                                       target:nil action:nil];
//    
//    /**
//     
//     *  width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和边界间距为5pix，所以width设为-5时，间距正好调整
//     
//     *  为0；width为正数时，正好相反，相当于往左移动width数值个像素
//     
//     */
//    
//    negativeSpacerLeft.width = -15;
//    
//    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerLeft, backItem, nil];
//
    

    
    
    //底层NavigationView
    self.NavigationView  = [[UIView  alloc]init];
    self.NavigationView.frame = CGRectMake(0, 0, 120, 44);
    self.NavigationView.backgroundColor =[UIColor clearColor];
 

    
    //右边负责人按钮
    self.NavContact = [UIButton buttonWithType:UIButtonTypeCustom];
    self.NavContact.frame = CGRectMake(0,4, 40, 35);
    [self.NavContact setImage:[UIImage imageNamed:@"action_servicer@2x"] forState:UIControlStateNormal];
    [self.NavContact setImage:[UIImage imageNamed:@"action_servicer_h@2x"] forState:UIControlStateHighlighted];
    self.NavContact.tag = 0;
    [self.NavContact addTarget:self action:@selector(NavButseletor:) forControlEvents:UIControlEventTouchUpInside];
    [self.NavigationView addSubview:self.NavContact];


    
    //右边导航按钮
    self.NavBut = [UIButton buttonWithType:UIButtonTypeCustom];
    self.NavBut.frame = CGRectMake(120-80,4, 40, 35);
    [self.NavBut setImage:[UIImage imageNamed:@"top_navgation@2x"] forState:UIControlStateNormal];
    [self.NavBut setImage:[UIImage imageNamed:@"top_navgation_h@2x"] forState:UIControlStateHighlighted];
    //[self.NavBut setBackgroundColor:[UIColor greenColor]];
    self.NavBut.tag = 1;
    [self.NavBut addTarget:self action:@selector(NavButseletor:) forControlEvents:UIControlEventTouchUpInside];
    [self.NavigationView addSubview:self.NavBut];
    
    
    
    
    //右边菜单按钮
    
    self.NavButMenu = [UIButton buttonWithType:UIButtonTypeCustom];
    self.NavButMenu.frame = CGRectMake(120-40, 4, 40, 35);
    [self.NavButMenu setImage:[UIImage imageNamed:@"top_more@2x"] forState:UIControlStateNormal];
    [self.NavButMenu setImage:[UIImage imageNamed:@"top_more_h@2x"] forState:UIControlStateHighlighted];
    self.NavButMenu.tag = 2;
    //[self.NavButMenu setBackgroundColor:[UIColor redColor]];
    [self.NavButMenu addTarget:self action:@selector(NavButseletor:) forControlEvents:UIControlEventTouchUpInside];
    [self.NavigationView addSubview:self.NavButMenu];
    
//    
//    MenuView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, 100, 150)];
//    MenuView.backgroundColor = [UIColor grayColor];
//    [self.view addSubview:MenuView];
//    MenuView.hidden = YES;
   
    
    UIBarButtonItem *negativeSpacerRight = [[UIBarButtonItem alloc]
                                       
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       
                                       target:nil action:nil];
    
    /**
     
     *  width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和边界间距为5pix，所以width设为-5时，间距正好调整
     
     *  为0；width为正数时，正好相反，相当于往左移动width数值个像素
     
     */
    
    negativeSpacerRight.width = -15;
    
    UIBarButtonItem *rightBarBtItem = [[UIBarButtonItem alloc] initWithCustomView: self.NavigationView];
    
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacerRight, rightBarBtItem, nil];


    
    
    
    
    
    
}

#pragma mark 导航栏控件button的代理

-(void)NavButseletor:(UIButton *)But
{

    if(But.tag == 0)
    {
        ContactViewController   *ContactView = [[ContactViewController alloc]init];
        [self.navigationController pushViewController:ContactView animated:YES];
    
    }else if (But.tag == 1)
    {
        NavRootShowViewContorller   *NavShowView = [[NavRootShowViewContorller alloc]init];
        [self.navigationController pushViewController:NavShowView animated:YES];
    
    }else if (But.tag == 2)
    {
        [self ViewShowControll];
        
    }
    

}
#pragma mark 导航栏菜单的弹出视图
-(void)ViewShowControll
{


    backgroundView =[[UIControl alloc]initWithFrame:self.view.bounds];
    [backgroundView addTarget:self action:@selector(RemoverSelf:) forControlEvents:UIControlEventTouchUpInside];
    backgroundView.backgroundColor =[UIColor clearColor];
    backgroundView.alpha = 0;
    [[UIApplication sharedApplication].keyWindow addSubview:backgroundView];
    [UIView animateWithDuration:0.3
                     animations:^{
                         
                         backgroundView.alpha = 1;
                         
                         
                     }];

    
    
    //搜索
    UIControl *ControlBut0 =[[UIControl alloc]initWithFrame:CGRectMake(Dev_ScreenWidth-120-5, 20, 120, 40)];
    [ControlBut0 addTarget:self action:@selector(ButmenuFantion:) forControlEvents:UIControlEventTouchUpInside];
    ControlBut0.backgroundColor =[UIColor whiteColor];
    [backgroundView addSubview:ControlBut0];
    ControlBut0.tag =0;
    
    
    UIImageView *imagviewconten0 =[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 30, 30)];
    //imagviewconten.isUserInteractionEnabled =NO;
    imagviewconten0.image  = [UIImage imageNamed:@"action_search_overflow.png"];
    [ControlBut0 addSubview:imagviewconten0];
    
    
    
    UILabel *labelTitle0 = [[UILabel alloc] initWithFrame:CGRectMake(40+10, 0, 70, 40)];
    labelTitle0.font = [UIFont boldSystemFontOfSize:16.0];  //UILabel的字体大小
    labelTitle0.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
    //        labelTitle.textColor = RGBCOLOR(0, 0, 147);
    labelTitle0.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    //[labelTitle setBackgroundColor:[UIColor redColor]];
    labelTitle0.text =@"搜索";
    [ControlBut0 addSubview:labelTitle0];

    
    
    
    
    
    
    
    
    //留言管理
    UIControl *ControlBut1 =[[UIControl alloc]initWithFrame:CGRectMake(Dev_ScreenWidth-120-5, 60, 120, 40)];
    [ControlBut1 addTarget:self action:@selector(ButmenuFantion:) forControlEvents:UIControlEventTouchUpInside];
    ControlBut1.backgroundColor =[UIColor whiteColor];
    [backgroundView addSubview:ControlBut1];
    ControlBut1.tag =1;
    
    UIImageView *imagviewconten1 =[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 30, 30)];
    //imagviewconten.isUserInteractionEnabled =NO;
    imagviewconten1.image  = [UIImage imageNamed:@"action_message.png"];
    [ControlBut1 addSubview:imagviewconten1];
    
    
    
    UILabel *labelTitle1 = [[UILabel alloc] initWithFrame:CGRectMake(40+10, 0, 70, 40)];
    labelTitle1.font = [UIFont boldSystemFontOfSize:16.0];  //UILabel的字体大小
    labelTitle1.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
    //        labelTitle.textColor = RGBCOLOR(0, 0, 147);
    labelTitle1.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    //[labelTitle setBackgroundColor:[UIColor redColor]];
    labelTitle1.text =@"留言管理";
    [ControlBut1 addSubview:labelTitle1];

    
    
    
    
    
    
    //设置
    UIControl *ControlBut2 =[[UIControl alloc]initWithFrame:CGRectMake(Dev_ScreenWidth-120-5, 100, 120, 40)];
    [ControlBut2 addTarget:self action:@selector(ButmenuFantion:) forControlEvents:UIControlEventTouchUpInside];
    ControlBut2.backgroundColor =[UIColor whiteColor];
    [backgroundView addSubview:ControlBut2];
    ControlBut2.tag =2;
    
    UIImageView *imagviewconten2 =[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 30, 30)];
    //imagviewconten.isUserInteractionEnabled =NO;
    imagviewconten2.image  = [UIImage imageNamed:@"action_settings.png"];
    [ControlBut2 addSubview:imagviewconten2];
    
    
    
    UILabel *labelTitle2 = [[UILabel alloc] initWithFrame:CGRectMake(40+10, 0, 70, 40)];
    labelTitle2.font = [UIFont boldSystemFontOfSize:16.0];  //UILabel的字体大小
    labelTitle2.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
    //        labelTitle.textColor = RGBCOLOR(0, 0, 147);
    labelTitle2.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    //[labelTitle setBackgroundColor:[UIColor redColor]];
    labelTitle2.text =@"设置";
    [ControlBut2 addSubview:labelTitle2];
    
    
    
    
    
    
    
    
    
    //注销or登录
    UIControl *ControlBut3 =[[UIControl alloc]initWithFrame:CGRectMake(Dev_ScreenWidth-120-5, 140, 120, 40)];
    [ControlBut3 addTarget:self action:@selector(ButmenuFantion:) forControlEvents:UIControlEventTouchUpInside];
    ControlBut3.backgroundColor =[UIColor whiteColor];
    [backgroundView addSubview:ControlBut3];
    ControlBut3.tag =3;
    
    
    NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
    if([userdefaults objectForKey:YZZX_Login_user_id]!=nil)
    {

        UIImageView *imagviewconten3 =[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 30, 30)];
        //imagviewconten.isUserInteractionEnabled =NO;
        imagviewconten3.image  = [UIImage imageNamed:@"action_logout.png"];//action_login 登录
        [ControlBut3 addSubview:imagviewconten3];
        
        
        
        UILabel *labelTitle3 = [[UILabel alloc] initWithFrame:CGRectMake(40+10, 0, 70, 40)];
        labelTitle3.font = [UIFont boldSystemFontOfSize:16.0];  //UILabel的字体大小
        labelTitle3.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
        //        labelTitle.textColor = RGBCOLOR(0, 0, 147);
        labelTitle3.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
        //[labelTitle setBackgroundColor:[UIColor redColor]];
        labelTitle3.text =@"注销";
        [ControlBut3 addSubview:labelTitle3];
        
        
        
    }else if([userdefaults objectForKey:YZZX_Login_user_id]==nil)
    {
        
        UIImageView *imagviewconten3 =[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 30, 30)];
        //imagviewconten.isUserInteractionEnabled =NO;
        imagviewconten3.image  = [UIImage imageNamed:@"action_login.png"];//action_login 登录
        [ControlBut3 addSubview:imagviewconten3];
        
        
        
        UILabel *labelTitle3 = [[UILabel alloc] initWithFrame:CGRectMake(40+10, 0, 70, 40)];
        labelTitle3.font = [UIFont boldSystemFontOfSize:16.0];  //UILabel的字体大小
        labelTitle3.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
        //        labelTitle.textColor = RGBCOLOR(0, 0, 147);
        labelTitle3.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
        //[labelTitle setBackgroundColor:[UIColor redColor]];
        labelTitle3.text =@"登录";
        [ControlBut3 addSubview:labelTitle3];
 
    }

}

#pragma mark 导航栏菜单的弹出视图remover
-(void)RemoverSelf:(UIControl *)controll
{
    [controll removeFromSuperview];
}


-(void)ButmenuFantion:(UIControl *)ContrllTag
{
    
    [backgroundView removeFromSuperview];
    
  if(ContrllTag.tag ==0)
  {
      //搜索
      [self searchDataTableViewShow];
      [TextSearchView becomeFirstResponder];
  
  }else if (ContrllTag.tag==1)
  {
      MessageManagementVC  *viewmessage = [[MessageManagementVC alloc]init];
      [self.navigationController pushViewController:viewmessage animated:YES];
      
  
  }else if (ContrllTag.tag==2)
  {
      
  
      AttributeModelVC  *attrisett =[[AttributeModelVC alloc]init];
      attrisett.Viewdegat = self;
      [self.navigationController pushViewController:attrisett animated:YES];
  
  }else if (ContrllTag.tag==3)
  {

     
      if(![[XSZ_UICommon useridChangUaerdfLoginBoolString] isEqualToString:@""])
      {
          
          
          UIAlertView  *AlertView = [[UIAlertView alloc]initWithTitle:@"注销"
                                                              message:@"确定要注销吗？"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                                    otherButtonTitles:@"确定",nil];
          
          AlertView.tag = 101;
          [AlertView show];
          return;
          
          
          
      }else if([[XSZ_UICommon useridChangUaerdfLoginBoolString] isEqualToString:@""])
      {
          //登录
          LoginViewController  *LoginView =[[LoginViewController alloc]init];
          LoginView.Viewdegat = self;
          [self.navigationController pushViewController:LoginView animated:YES];
      }

  }


}



#pragma mark alertView 弹框代理+功能 +注销
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if(alertView.tag == 101)
    {
        if(buttonIndex == 0)
        {
        //取消则不清除缓存

            
        }else if (buttonIndex == 1)
        {
            
            NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
            //注销
            [userdefaults setObject:nil forKey:YZZX_Login_user_id];
            [userdefaults setObject:nil forKey:YZZX_Login_fullname];
            [userdefaults setObject:nil forKey:YZZX_Login_site_id];

        
        }
    }
    
}


#pragma mark  搜索功能
-(void)searchDataTableViewShow
{

    SearchView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, 64)];
    SearchView.backgroundColor = RGBCOLOR(252, 115, 148);
    [[UIApplication sharedApplication].keyWindow addSubview:SearchView];
    
    UIButton  *ButBcak =[[UIButton alloc]initWithFrame:CGRectMake(0, 20, 44, 44)];
    [ButBcak addTarget:self action:@selector(removeSearchView) forControlEvents:UIControlEventTouchUpInside];
    [ButBcak setBackgroundImage:[UIImage imageNamed:@"top_navgation_back@2x.png"] forState:UIControlStateNormal];
    [ButBcak setBackgroundImage:[UIImage imageNamed:@"top_navgation_back_h@2x.png"] forState:UIControlStateHighlighted];
    [SearchView addSubview:ButBcak];
    
    TextSearchView =[[UITextField alloc]initWithFrame:CGRectMake(50, 30, Dev_ScreenWidth-60-44, 25)];
    TextSearchView.delegate = self;
   // TextSearchView.backgroundColor = [UIColor greenColor];
    
    //再次编辑就清空
    TextSearchView.clearsOnBeginEditing = YES;
    //用于一次性删除输入框中的内容
    TextSearchView.clearButtonMode = UITextFieldViewModeAlways;
    //当输入框没有内容时，水印提示
    TextSearchView.placeholder = @"请输入搜索条件";
    TextSearchView.textColor = [UIColor whiteColor];
    [SearchView addSubview:TextSearchView];

    UIView  *LineView =[[UIView alloc]initWithFrame:CGRectMake(50, 30+26, Dev_ScreenWidth-60-44, 1)];
    LineView.backgroundColor = [UIColor whiteColor];//RGBCOLOR(0, 41, 112);
    [SearchView addSubview:LineView];
    
    
    UIButton  *ButSearch =[[UIButton alloc]initWithFrame:CGRectMake(Dev_ScreenWidth-50, 25, 40, 35)];
    [ButSearch addTarget:self action:@selector(searchModelDataRelodeTableView) forControlEvents:UIControlEventTouchUpInside];
    [ButSearch setBackgroundImage:[UIImage imageNamed:@"action_search.png"] forState:UIControlStateNormal];
    [SearchView addSubview:ButSearch];
    //ButSearch.backgroundColor =[UIColor redColor];
    //ButSearch.backgroundColor =[UIColor greenColor];

}

-(void)removeSearchView
{
    [SearchView removeFromSuperview];
}

-(void)searchModelDataRelodeTableView
{
    [self.mainController TheColumnSize:TextSearchView.text];
     [TextSearchView resignFirstResponder];
     [SearchView removeFromSuperview];
}





#pragma mark  添加到viewcontorller 上的手势
- (void)rightBgControlAction
{
    [self hideLeftView];
}




#pragma mark  导航栏 切换子视图 执行的动画效果（Push）
- (CABasicAnimation *)selfBgShowAnimation
{
    CABasicAnimation *baseAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
    baseAnimation.fromValue = (__bridge id)([UIColor colorWithRed:28.0f/255.0f
                                                            green:28.0f/255.0f
                                                             blue:28.0f/255.0f
                                                            alpha:0.0f].CGColor);
    baseAnimation.toValue = (__bridge id)([UIColor colorWithRed:28.0f/255.0f
                                                          green:28.0f/255.0f
                                                           blue:28.0f/255.0f
                                                          alpha:0.3f].CGColor);
    baseAnimation.duration = .35f;
    baseAnimation.fillMode = kCAFillModeForwards;
    baseAnimation.removedOnCompletion = NO;
    return baseAnimation;
}

#pragma mark  导航栏 切换子视图 执行的动画效果（Hide）
- (CABasicAnimation *)selfBgHideAnimation
{
    CABasicAnimation *baseAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
    baseAnimation.fromValue = (__bridge id)([UIColor colorWithRed:28.0f/255.0f
                                                            green:28.0f/255.0f
                                                             blue:28.0f/255.0f
                                                            alpha:0.3f].CGColor);
    baseAnimation.toValue = (__bridge id)([UIColor clearColor].CGColor);
    baseAnimation.duration = .35f;
    baseAnimation.fillMode = kCAFillModeForwards;
    baseAnimation.removedOnCompletion = NO;
    baseAnimation.delegate = self;
    return baseAnimation;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (_rightBgControl != nil)
    {
        [_rightBgControl removeFromSuperview], _rightBgControl = nil;
    }
}




#pragma mark  导航栏 切换子视图的  右边的菜单按钮
-(void)Menuseletor: (UIButton *)but
{
    
    if (_mainView.left == 200)
    {
        [self hideLeftView];
    }else if (_mainView.left < 200)
    {
        [self showLeftView];
    }
    
    
}



- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.navigationController.interactivePopGestureRecognizer.delegate =self;
//     self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    _ChangNavTag = 1024;   //初始化标记
    
    
    //一个通知 栏目跳转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:)name:YZZX_LANMU_CHANG object:nil];
    
    
    //一个通知 登录成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFantion)name:YZZX_LANMU_CHANG object:nil];
    
    
    

    
    ViewArry = [[NSMutableArray alloc]init];
    ViewimageArry = [[NSMutableArray alloc]init];

    [self NavController];
    
    if(self.ModelData == nil)
    {
        [self changeLeftItemandSiteID:@"1"];
    }
    
}


- (void)viewWillAppear:(BOOL)animated
{
    
    //设置导航栏的固定色值
    self.navigationController.navigationBar.barTintColor = RGBCOLOR(252, 115, 148);
    
    if(Dev_ScreenWidth==320)
    {
     self.navigationController.navigationBar.barTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"NavBarbackground_5s@2x.png"]];
    }else if(Dev_ScreenWidth==375)
    {
     self.navigationController.navigationBar.barTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"NavBarbackground_6@2x.png"]];
    }else if(Dev_ScreenWidth==414)
    {
     self.navigationController.navigationBar.barTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"NavBarbackground_6m@3x.png"]];

    }
        

 }


#pragma mark push详细页面代理 (ListTableview)
-(void)PushViewContorllerDataModel:(YZCellMassgeModel *)model
{
    
    MassgeViewModelVC  *massgeview = [[MassgeViewModelVC alloc]initWithEstablish:model];
    massgeview.Viewdegat = self;
    [self.navigationController pushViewController:massgeview animated:YES];
    
    
}
#pragma mark push详细页面代理 (zlineView)
- (void)pushViewContorllDelegat:(ZilneListDataModel*)Model
{
    
    ListZilneVC  *zlieview =[[ListZilneVC alloc]init];
    zlieview.mdoeldata =Model;
    [self.navigationController pushViewController:zlieview animated:YES];
   
}
    



#pragma mark 根据 API固定SiteID 传入一个ID，返回，categorymodel 树形 数组
- (void)changeLeftItemandSiteID:(NSString *)strSiteID
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSArray *cacheCateList = [CategoryDataModel getCategoryListWithWebsiteID:strSiteID];
    if (!ArrayIsEmpty(cacheCateList))
    {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        //如果有数据，则取第一个 栏目的数据，传给manview
        if(self.ModelData == nil)
        {
            self.ModelData =[[NSArray alloc]initWithArray:cacheCateList];
        }
        
   
        
        CategoryDataModel * mdoeldata = [cacheCateList objectAtIndex:0];
        [self guanzhuMantabbarGetDataArryforCategory:mdoeldata.children];
        
    } else
    {
        // 没有数据则请求数据，缓存，再传数据给manview
        
        //[HXTool showHud:self.view WithTitle:@"请稍后..." animated:YES andIsShowDimBackGound:NO];
        [CategoryDataModel categoryListRequestWithWebsiteID:strSiteID complateAction:^(NSArray *cateList, NSString *errMsg)
         {
             
             // [HXTool hideHud:self.view animated:YES];
             if (errMsg)
             {

                 
                 //[HXTool tipWithMsg:errMsg inView:self.view];
             } else if (!ArrayIsEmpty(cateList))
             {
                 

                 dispatch_main_async_safe(^{
                  
                     [MBProgressHUD hideHUDForView:self.view animated:YES];
                     //必须在main里面刷新UI
                    //如果有数据，则取第一个 栏目的数据，传给manview
                     if(self.ModelData == nil)
                     {
                      self.ModelData =[[NSArray alloc]initWithArray:cateList];
                     }
                     
                     CategoryDataModel * mdoeldata = [cateList objectAtIndex:0];
                     //  [self initializeSubview:mdoeldata.children];
                     [self guanzhuMantabbarGetDataArryforCategory:mdoeldata.children];
                     
                 });

             }
         }];
    }
    
}

#pragma mark 通知代理 登录成功
- (void)loginFantion
{
//   [backgroundView removeFromSuperview];

}





#pragma mark 通知代理 传值数据处理

- (void)tongzhi:(NSNotification *)text
{
    
    NSLog(@"%@",text.userInfo[@"textOne"]);
    [self changeCategoryWithID:[text.userInfo[@"cate_id"] intValue]];
}

- (void)changeCategoryWithID:(int)cateID
{
    
    CategoryDataModel *cateListModel = nil;
    for (int _indexCate = 0; _indexCate < self.ModelData.count; _indexCate++)
    {
        cateListModel = [self queryCateModelWithCateID:cateID InCategoryListModel:self.ModelData[_indexCate]];
        if (cateListModel != nil)
        {
            //包含tabbar的molde  ---cateDataModel
             CategoryDataModel *cateDataModel =  self.ModelData[_indexCate];
            for (int i = 0;i<cateDataModel.children.count;i++)
            {
                //包含tabbar其中的一个itme的molde  ---ViewTileModel
                CategoryDataModel * ViewTileModel = cateDataModel.children[i];
               
                if([ViewTileModel.cate_id intValue] == cateID)
                {
                    //切换视图
                    [self ChangMainViewContorllerDataAndUIModelTag:_indexCate];
                    //切换tabbaritim
                    [self.mainController setSelectedIndex:i];
                    
                    
                    
                    
                    
                    // 发完通知后，中断循环，因为已经找到了，并且跳转了
                    //在各类实例化完成后，调用通知，让leftView的cell改变
                    //创建通知
                    NSString *strtag =[NSString stringWithFormat:@"%d",_indexCate];
                    NSDictionary *dicD =[[NSDictionary alloc]initWithObjectsAndKeys:strtag,@"Tag", nil];
                    NSNotification *notification =[NSNotification notificationWithName:YZZX_LEFT_CELL_CHANG object:nil userInfo:dicD];
                    //通过通知中心发送通知
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                     return;
                    
                    
                    
                    
                }else if([ViewTileModel.cate_id intValue] != cateID && ViewTileModel.children!=nil)
                {
                    
                    for (int  _TagIndex = 0;_TagIndex<ViewTileModel.children.count;_TagIndex++)
                    {
                        //包含tabbar的itme的里面的分栏的molde  ---NavModel
                        CategoryDataModel * NavModel = ViewTileModel.children[_TagIndex];
                        
                        if([NavModel.cate_id intValue] == cateID)
                        {
                            //切换视图
                            [self ChangMainViewContorllerDataAndUIModelTag:_indexCate];
                            //切换tabbaritim
                            [self.mainController setSelectedIndex:i];
                            //切换栏目
                            SuperBarVC *view = [self.mainController.viewControllersArray objectAtIndex:i];
                           [view ButfantionNavTiaozhuan:_TagIndex];
                            
                       
                            // 发完通知后，中断循环，因为已经找到了，并且跳转了
                            // NSString *strTag = [_indexCate stringV]
                            //在各类实例化完成后，调用通知，让leftView的cell改变
                        
                            //创建通知
                            NSString *strtag =[NSString stringWithFormat:@"%d",_indexCate];
                            NSDictionary *dicD =[[NSDictionary alloc]initWithObjectsAndKeys:strtag,@"Tag", nil];
                            
                            NSNotification *notification =[NSNotification notificationWithName:YZZX_LEFT_CELL_CHANG object:nil userInfo:dicD];
                            //通过通知中心发送通知
                            [[NSNotificationCenter defaultCenter] postNotification:notification];
                             return;
                            
                        }
                    
                    }
                }
            }
          
          
          
            
        }
        
    }
}


/**
 *  寻找对应栏目ID在指定栏目下是否存在
 */

- (CategoryDataModel *)queryCateModelWithCateID:(int)cateID InCategoryListModel:(CategoryDataModel *)categoryListModel
{
    CategoryDataModel *cateListModel = nil;
    if ([categoryListModel.cate_id intValue] == cateID)
    {
        cateListModel = categoryListModel;
    } else
    {
        if (!ArrayIsEmpty(categoryListModel.children))
        {
            for (CategoryDataModel *model in categoryListModel.children)
            {
                cateListModel = [self queryCateModelWithCateID:cateID InCategoryListModel:model];
                if (ObjectIsValid(cateListModel))
                    break;
            }
        }
    }
    return cateListModel;
}



#pragma mark textfild 代理回收键盘

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [TextSearchView resignFirstResponder];
  
    return YES;
}







@end
